#include <c++/cstring>
#include <c++/queue>
using namespace std;


//Definition for a binary tree node.
struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

const int N=1000010;
int h[N];
int e[N*2];
int ne[N*2];
int idx;
int dist[N];


class Solution{
public:

    void add(int a,int b){
        e[idx]=b;
        ne[idx]=h[a];
        h[a]=idx++;
    }

    void dfs(TreeNode* root){
        if(root->left){
            add(root->val,root->left->val);
            add(root->left->val,root->val);
            dfs(root->left);
        }
        if(root->right){
            add(root->val,root->right->val);
            add(root->right->val,root->val);
            dfs(root->right);
        }
    }

    int amountOfTime(TreeNode* root, int start) {
        memset(h,-1, sizeof h);
        idx=0;
        dfs(root);
        queue<int> q;
        q.push(start);
        memset(dist,0x3f,sizeof dist);
        dist[start]=0;
        int res=0;
        while(q.size()){
            auto t =q.front();
            q.pop();
            res=max(res,dist[t]);
            for (int i = h[t]; ~i ;i =ne[i]) {
                int j=e[i];
                if(dist[j]>dist[t]+1){
                    dist[j]=dist[t]+1;
                    q.push(j);
                }
            }
        }
        return res;
    }
};